package com.xuzhijie.pms.config.interceptor;

import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.xuzhijie.pms.PmsProjectApplication;
import com.xuzhijie.pms.common.Constants;
import com.xuzhijie.pms.entity.Administrator;
import com.xuzhijie.pms.entity.Owner;
import com.xuzhijie.pms.exception.PmsServerException;
import com.xuzhijie.pms.service.IAdministratorService;
import com.xuzhijie.pms.service.IOwnerService;
import com.xuzhijie.pms.service.impl.OwnerServiceImpl;
import com.xuzhijie.pms.utils.JwtUtils;
import com.xuzhijie.pms.utils.ThreadLocalUtil;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class JWTInterceptors implements HandlerInterceptor {

    @Resource
    private IAdministratorService service;

    @Resource
    private IOwnerService iOwnerService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler){

        String token = request.getHeader("token");
        System.out.println(request.getRequestURL().toString());
        if (!(handler instanceof HandlerMethod)) {

//            System.out.println("请求是映射方法");
            return true;
        }
//        System.out.println("请求不是映射方法");

        //验证是否又token
        if (StrUtil.isBlank(token)) {
//            System.out.println("没有token");
            throw new PmsServerException("过期请重新登陆", Constants.CODE_401);
        }
//        System.out.println("token存在");



        //获取id，判断是否存在
        String userId = JwtUtils.getUserIdFromToken(token);
//        System.out.println("解析token成功");

        // 查询数据库判断用户是否存在
        Administrator admin;
        Owner owner;
        try {
//            System.out.println("用户存在");
//            System.out.println("userId:"+userId);
            admin = service.getById(userId);
            owner = iOwnerService.getById(userId);
//            System.out.println("admin："+admin);
        }catch (Exception e) {
            String errMsg = "token验证失败，请重新登录";
            throw new PmsServerException(errMsg, Constants.CODE_401);
        }

        if (admin == null && owner == null) {

//            System.out.println("用户不存在");
            throw new PmsServerException("用户不存在，请重新登陆", Constants.CODE_401);
        }

        if (admin != null){
            JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(admin.getSalt())).build();
            try {
                jwtVerifier.verify(token);
            } catch (JWTVerificationException e) {
                throw new PmsServerException("登陆已过期，请重新登录", Constants.CODE_401);
            }
            ThreadLocalUtil.addCurrentUser(admin);
        }

        if (owner != null){
            JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(owner.getSalt())).build();
            try {
                jwtVerifier.verify(token);
            } catch (JWTVerificationException e) {
                throw new PmsServerException("登陆已过期，请重新登录", Constants.CODE_401);
            }
        }


        return true;
    }
}
